/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact z_huatai@qq.com
 *  
 */
package org.zfes.snowy.generate.interfaces;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import org.zfes.snowy.generate.config.GenFreemarkerConfig;
import org.zfes.snowy.generate.exceptions.GenerationException;

import freemarker.template.Template;

public abstract class AbstractGenerator implements Generator {

	@SuppressWarnings("deprecation")
	@Override
	public void generate(String tplFullPathFileName, Map<?,?> data,String outPutfileFullPathName) {
		try {
			String templateFileDir=tplFullPathFileName.substring(0, tplFullPathFileName.lastIndexOf("/"));
			String templateFile=tplFullPathFileName.substring(tplFullPathFileName.lastIndexOf("/")+1, tplFullPathFileName.length());
			
			String genFileDir=outPutfileFullPathName.substring(0, outPutfileFullPathName.lastIndexOf("/"));
	        Template template = GenFreemarkerConfig.getConfiguration(templateFileDir).getTemplate(templateFile);
	        template.setEncoding("UTF-8");
	        org.apache.commons.io.FileUtils.forceMkdir(new File(genFileDir));
	        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outPutfileFullPathName),"UTF-8"));
	        template.process(data, writer);
	        writer.close();
		} catch (Exception e) {
			throw new GenerationException("生成过程错误: "+e.getMessage());
		}
	}
	@Override
	public void generate2(String tplPath,String tplFileName,String outPutfileFullPathName, Map<?,?> data) {
		try {
			String genFileDir=outPutfileFullPathName.substring(0, outPutfileFullPathName.lastIndexOf("/"));
			
			Template template =GenFreemarkerConfig.getTemplate(tplPath, tplFileName);
			org.apache.commons.io.FileUtils.forceMkdir(new File(genFileDir));
		    Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outPutfileFullPathName),"UTF-8"));
		    template.process(data, writer);
		    writer.close();
		        
		} catch (Exception e) {
			throw new GenerationException("生成过程错误: "+e.getMessage());
		}
	}
}
